﻿using System.Linq;
using NHibernate;
using NHibernate.Linq;
using Wayloop.Blog.Core.Data;
using Wayloop.Blog.Core.Data.Entities;


namespace Wayloop.Blog.DataAccess.Repositories
{
    public abstract class AbstractRepository<TEntity> : IRepository<TEntity> where TEntity : AbstractEntity
    {
        protected ISession Session
        {
            get { return SessionHandlerModule.CurrentSession; }
        }


        public virtual TEntity Find(int id)
        {
            return FindAll().SingleOrDefault(x => x.Id == id);
        }


        public virtual IQueryable<TEntity> FindAll()
        {
            INHibernateQueryable<TEntity> entities = Session.Linq<TEntity>();
            entities.QueryOptions.SetCachable(true);

            return from entity in entities
                   select entity;
        }


        public virtual IQueryable<TEntity> FindAll(int pageIndex, int pageSize)
        {
            return FindAll().Skip(pageIndex * pageSize).Take(pageSize);
        }


        public virtual void Save(TEntity entity)
        {
            Session.SaveOrUpdate(entity);
        }


        public virtual void Delete(TEntity entity)
        {
            Session.Delete(entity);
        }


        public virtual void Refresh(TEntity entity)
        {
            Session.Refresh(entity);
        }
    }
}